const orderModel = require('../modules/orderModel');

const db = {};
//factor
db.query = async ({ query = { userId: null }, current = { page: 0, count: 0 } }) => {
    let count = await orderModel.countDocuments();
    let result;
    if (query.userId) {
        result = await orderModel
            .find({ status: { $nin: [0] } }, { id: 0 })
            .or([{ borrowId: query.userId }, { returnId: query.userId }])
            .populate([{ path: 'borrowId', select: { userName: 1, _id: 0, iphone: 1 } }, { path: 'returnId', select: { userName: 1, _id: 0, iphone: 1 } }, { path: 'carId' }])
            .skip((current.page - 1) * current.count)
            .limit(current.count);

        return {
            code: 1,
            message: '查询成功',
            result: {
                count,
                length: result.length,
                orderList: result,
            },
        };
    } else {
        result = await orderModel
            .find({ status: { $nin: [0] } }, { id: 0 })
            .populate([{ path: 'borrowId', select: { userName: 1, _id: 0, iphone: 1 } }, { path: 'returnId', select: { userName: 1, _id: 0, iphone: 1 } }, { path: 'carId' }])
            .skip((current.page - 1) * current.count)
            .limit(current.count);

        return {
            code: 1,
            message: '查询成功',
            result: {
                count,
                length: result.length,
                orderList: result,
            },
        };
    }
};

db.create = async (body) => {
    try {
        let result = await orderModel.create(body);
        return {
            code: 1,
            message: '创建订单成功',
            result,
        };
    } catch (e) {
        console.log(e);
        return {
            code: 0,
            message: e._message,
        };
    }
};

db.update = async ({ query = { _id: null }, data = {} }) => {
    try {
        console.log(query, data);
        let result = await orderModel.update(query, data);
        return {
            code: 1,
            message: '修改订单成功',
            result,
        };
    } catch (e) {
        return {
            code: 0,
            message: e._message,
        };
    }
};

module.exports = db;
